import { Injectable } from '@nestjs/common';
import { CreateMercadoskuDto } from 'src/dto/create-mercadosku.dto';
import { UpdateMercadoskuDto } from 'src/dto/update-mercadosku.dto';
import { Mercadosku } from 'src/entity/mercadosku.entity';
import { QueryMercadoskuDto } from 'src/dto/query-mercadosku.dto';
import { parseQueryParams } from 'src/common/utils';
import { Mercadoproduct } from 'src/entity/mercadoproduct.entity';

@Injectable()
export class MercadoskuService {
  async create(createMercadoskuDto: CreateMercadoskuDto) {
    let mercadoproduct = await Mercadoproduct.findOne({
      where: { id: createMercadoskuDto.mercadoproductId },
    });

    let mercadosku = Mercadosku.create({
      name: createMercadoskuDto.name,
      mercadoNumber: createMercadoskuDto.mercadoNumber,
      number: createMercadoskuDto.number,
      image: createMercadoskuDto.image,
      purchasePrice: createMercadoskuDto.purchasePrice,
      salePrice: createMercadoskuDto.salePrice,
    });

    // mercadoproduct
    mercadosku.mercadoproduct = mercadoproduct;

    return mercadosku.save();
  }

  async findAll(pageNum: number, pageSize: number) {
    const [list, count] = await Mercadosku.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    });

    return { list, count };
  }

  async query(query: QueryMercadoskuDto) {
    let qeryBuilder = Mercadosku.createQueryBuilder('mercadosku');

    let { queryClone, pageNum, pageSize } = parseQueryParams(query, [
      'mercadoproductId',
    ]);

    qeryBuilder.where(queryClone);

    // qeryBuilder.leftJoinAndSelect(
    //   'mercadosku.mercadoproduct',
    //   'mercadoproduct',
    // );

    // 关联查询
    if (query.mercadoproductId) {
      qeryBuilder
        .leftJoinAndSelect('mercadosku.mercadoproduct', 'mercadoproduct')
        .leftJoinAndSelect('mercadosku.boxs', 'boxs')
        .andWhere('mercadosku.mercadoproductId = :mercadoproductId', {
          mercadoproductId: query.mercadoproductId,
        });
    } else {
      qeryBuilder.leftJoinAndSelect(
        'mercadosku.mercadoproduct',
        'mercadoproduct',
      );

      qeryBuilder.leftJoinAndSelect('mercadosku.boxs', 'boxs');
    }

    qeryBuilder.skip((pageNum - 1) * pageSize);
    qeryBuilder.take(pageSize);
    qeryBuilder.orderBy('mercadosku.createTime', 'DESC');

    let [list, count] = await qeryBuilder.getManyAndCount();

    let calcList = [];

    for await (let item of list) {
      let obj = { ...item, stockBoxNum: 0, totalStockNum: 0 };

      obj.stockBoxNum = obj.boxs.reduce((pre, cur) => {
        if (cur.status == 1) {
          return pre + 1;
        } else {
          return pre;
        }
      }, 0);

      obj.totalStockNum = obj.boxs.reduce((pre, cur) => {
        if (cur.status == 1) {
          return pre + cur.boxNumber;
        } else {
          return pre;
        }
      }, 0);

      calcList.push(obj);
    }

    return { list: calcList, count };
  }

  async queryOrderByWarehouse(query: QueryMercadoskuDto) {
    let qeryBuilder = Mercadosku.createQueryBuilder('mercadosku');

    let { queryClone, pageNum, pageSize } = parseQueryParams(query, [
      'mercadoproductId',
    ]);

    qeryBuilder.where(queryClone);

    // 关联查询
    if (query.mercadoproductId) {
      qeryBuilder
        .leftJoinAndSelect('mercadosku.mercadoproduct', 'mercadoproduct')
        .leftJoinAndSelect('mercadosku.boxs', 'boxs')
        .leftJoinAndSelect('boxs.warehouse', 'warehouse')
        .andWhere('mercadosku.mercadoproductId = :mercadoproductId', {
          mercadoproductId: query.mercadoproductId,
        });
    } else {
      qeryBuilder.leftJoinAndSelect(
        'mercadosku.mercadoproduct',
        'mercadoproduct',
      );

      qeryBuilder.leftJoinAndSelect('mercadosku.boxs', 'boxs');
    }

    qeryBuilder.skip((pageNum - 1) * pageSize);
    qeryBuilder.take(pageSize);

    let [list, count] = await qeryBuilder.getManyAndCount();

    let warehouseList = [];
    list.map((item) => {
      item.boxs.map((box: any) => {
        if (box.status == 1) {
          let warehouse = box.warehouse;

          let index = warehouseList.find((item) => {
            return item.id == warehouse.id;
          });

          console.log('index', index);

          if (index == undefined) {
            let obj = {
              id: warehouse.id,
              name: warehouse.name,
              stockBoxNum: 1,
              totalStockNum: box.boxNumber,
              boxs: [box],
            };

            warehouseList.push(obj);
          } else {
            index.boxs.push(box);
            index.stockBoxNum = index.stockBoxNum + 1;
            index.totalStockNum = index.totalStockNum + box.boxNumber;
          }
        }
      });
    });

    return { warehouseList };
  }

  findOne(id: number) {
    return Mercadosku.findOneBy({ id });
  }

  async update(id: number, updateMercadoskuDto: UpdateMercadoskuDto) {
    let mercadoproduct = await Mercadoproduct.findOne({
      where: { id: updateMercadoskuDto.mercadoproductId },
    });

    delete updateMercadoskuDto.mercadoproductId;

    await Mercadosku.update(id, { ...updateMercadoskuDto });

    let mercadosku = await Mercadosku.findOneBy({ id });
    mercadosku.mercadoproduct = mercadoproduct;

    return mercadosku.save();
  }

  remove(id: number) {
    return Mercadosku.update(id, { deleteTime: new Date() });
  }
}
